package cn.easyplatform.studio.dao.impl.mysql;

import cn.easyplatform.studio.dao.DaoException;
import cn.easyplatform.studio.dao.DaoUtils;
import cn.easyplatform.studio.dao.Dialect;
import cn.easyplatform.studio.dao.impl.AbstractDatabaseUpdateDao;
import cn.easyplatform.studio.dao.transaction.JdbcTransactions;
import cn.hutool.db.dialect.impl.MysqlDialect;
import org.apache.commons.lang3.RandomStringUtils;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MySqlDatabaseUpdateDao extends AbstractDatabaseUpdateDao {
    /**
     * @param ds
     */
    public MySqlDatabaseUpdateDao(DataSource ds) {
        super(ds);
    }

    @Override
    protected Dialect getDialect() {
        return new MySqlDialect();
    }

    @Override
    protected String backup(String table, DataSource dataSource) {
        Statement stmt = null;
        try {
            Connection conn = JdbcTransactions.getConnection(dataSource);
            String tmpTable = table + "_"
                    + RandomStringUtils.randomAlphanumeric(10);
            StringBuilder sb = new StringBuilder();
            sb.append("CREATE TABLE ").append(tmpTable).append(" LIKE ").append(table);
            System.out.println("backup:" + sb.toString());
            stmt = conn.createStatement();
            stmt.execute(sb.toString());
            stmt.close();
            stmt = null;
            //插入表
            stmt = conn.createStatement();
            stmt.execute("insert into " + tmpTable + " select * from " + table);
            stmt.close();
            stmt = null;
            return tmpTable;
        } catch (SQLException ex) {
            throw new DaoException(ex.getMessage());
        } finally {
            DaoUtils.closeQuietly(stmt);
        }
    }

    @Override
    protected void restore(String source, String target, DataSource dataSource) {
        Statement stmt = null;
        try {
            Connection conn = JdbcTransactions.getConnection(dataSource);
            //删除表
            stmt = conn.createStatement();
            stmt.execute("drop table if exists " + target);
            stmt.close();
            stmt = null;
            //拷贝表
            StringBuilder sb = new StringBuilder();
            sb.append("CREATE TABLE ").append(target)
                    .append(" LIKE ").append(source);
            stmt = conn.createStatement();
            stmt.execute(sb.toString());
            stmt.close();
            stmt = null;
            //插入表
            stmt = conn.createStatement();
            stmt.execute("insert into " + target + " select * from " + source);
            stmt.close();
            stmt = null;
        } catch (SQLException ex) {
            throw new DaoException(ex.getMessage());
        } finally {
            DaoUtils.closeQuietly(stmt);
        }
    }
}
